package com.sunjob.mrosystem.bucketLimit;

import cn.dev33.satoken.stp.StpUtil;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-04 8:47
 * 基于令牌桶的限流器
 */
public class MROBucketLimit {
    // 桶
    private AtomicInteger bucket;
    private int capacity;
    public MROBucketLimit(int cap){
        this.capacity = cap;
        this.bucket = new AtomicInteger(cap);
    }
    public boolean acquire(){
        if(bucket.get()<=0){
            return false;
        }
        return bucket.decrementAndGet()>=0;
    }
    public void put(int i){
        if(bucket.get()>=capacity){
            // 多余抛弃
            return;
        }
        else{
            bucket.accumulateAndGet(i,(e1,e2)->{
                int t = e1+e2;
                if(t>=capacity){
                    // 多余的抛弃
                    t=capacity;
                }
                return t;
            });
        }
    }
}
